<template>
  <div class="search-container">
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 
      - 如果isResultShow为true，显示搜索结果
      - 否则如果searchText有内容，显示联想建议
      - 否则显示历史记录
     -->
    <!-- 搜索结果 -->
    <SearchResult v-if="isResultShow" :search-text="searchText" />
    <!-- 联想搜索 -->
    <SearchSuggestion
      :search-text="searchText"
      @search="onSearch"
      v-else-if="searchText"
    />
    <!-- 搜索历史 -->
    <SearchHistory
      v-else
      :search-histories="searchHistories"
      @clear-search-history="searchHistories = []"
      @search="onSearch"
    />
  </div>
</template>

<script>
import { getItem, setItem } from "@/utils/storage";
import SearchHistory from "./components/search-history.vue";
import SearchSuggestion from "./components/search-suggestion.vue";
import SearchResult from "./components/search-result.vue";
export default {
  name: "SearchIndex",
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [],
    };
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult,
  },
  methods: {
    onSearch(val) {
      this.searchText = val; //联想搜索框中的内容改为传递过来的内容
      this.isResultShow = true;
      const idx = this.searchHistories.indexOf(val);
      if (idx !== -1) {
        this.searchHistories.splice(idx, 1);
      }
      this.searchHistories.unshift(val);
    },
    onCancel() {
      this.$router.back();
    },
  },
  watch: {
    searchHistories(val) {
      setItem('TOUTIAO_SEARCH_HISTORIES', val)
    }
  }
};
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>>